package band.wukong.practice.javase.core.net.chat;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ChatClient {
    private JFrame frame;
    private JTextArea jta;
    private JTextField jtf;
    private Socket s;
    private BufferedReader in;
    private PrintWriter out;

    public void init() {
        frame = new JFrame("ChatClient");
        frame.setSize(400, 250);
        jta = new JTextArea();
        jta.setEditable(false);
        frame.add(new JScrollPane(jta));
        jtf = new JTextField();
        frame.add(jtf, "South");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        try {
            s = new Socket("localhost", 9000);
            out = new PrintWriter(s.getOutputStream());
            in = new BufferedReader(
                    new InputStreamReader(
                            s.getInputStream()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        jtf.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String text = jtf.getText();
                jtf.setText("");
                out.println(text);
                out.flush();
            }
        });
    }

    private void receiveText() {
        try {
            while (true) {
                String str = in.readLine();
                jta.append(str + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ChatClient() {
        init();
        receiveText();
    }

    public static void main(String[] args) {
        new ChatClient();
    }

}
